<template>
  <div class="monitor">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>执行监控</span>
        </div>
      </template>
      <el-table :data="tasks" style="width: 100%">
        <el-table-column prop="name" label="任务名称"></el-table-column>
        <el-table-column prop="status" label="状态" :formatter="statusFormatter"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="currentStep" label="当前步骤"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewLogs(scope.row.id)">查看日志</el-button>
            <el-button type="warning" size="small" @click="handlePause(scope.row.id)" :disabled="scope.row.status !== 1">暂停</el-button>
            <el-button type="success" size="small" @click="handleResume(scope.row.id)" :disabled="scope.row.status !== 5">恢复</el-button>
            <el-button type="danger" size="small" @click="handleStop(scope.row.id)" :disabled="scope.row.status !== 1 && scope.row.status !== 5">停止</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
          style="margin-top: 20px;"
      ></el-pagination>
    </el-card>

    <el-dialog title="任务日志" v-model="logsModalVisible" width="60%">
      <el-timeline>
        <el-timeline-item
            v-for="(log, index) in logs"
            :key="index"
            :timestamp="log.timestamp"
        >
          {{ log.message }}
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="logsModalVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Monitor',
  data() {
    return {
      tasks: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      logsModalVisible: false,
      logs: []
    };
  },
  mounted() {
    this.fetchTasks();
  },
  methods: {
    fetchTasks() {
      axios.get('/api/task', {
        params: {
          page: this.currentPage,
          size: this.pageSize
        },
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
          .then(response => {
            this.tasks = response.data.records;
            this.total = response.data.total;
          })
          .catch(error => {
            console.error('Error fetching tasks:', error);
          });
    },
    handlePageChange(val) {
      this.currentPage = val;
      this.fetchTasks();
    },
    handleViewLogs(taskId) {
      axios.get(`/api/log?taskId=${taskId}`, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
          .then(response => {
            this.logs = response.data;
            this.logsModalVisible = true;
          })
          .catch(error => {
            console.error('Error fetching logs:', error);
          });
    },
    handlePause(taskId) {
      axios.post(`/api/task/${taskId}/pause`, {}, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
          .then(response => {
            this.$message({
              type: 'success',
              message: '任务已暂停!'
            });
            this.fetchTasks();
          })
          .catch(error => {
            console.error('Error pausing task:', error);
          });
    },
    handleResume(taskId) {
      axios.post(`/api/task/${taskId}/resume`, {}, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
          .then(response => {
            this.$message({
              type: 'success',
              message: '任务已恢复!'
            });
            this.fetchTasks();
          })
          .catch(error => {
            console.error('Error resuming task:', error);
          });
    },
    handleStop(taskId) {
      axios.post(`/api/task/${taskId}/stop`, {}, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
          .then(response => {
            this.$message({
              type: 'success',
              message: '任务已停止!'
            });
            this.fetchTasks();
          })
          .catch(error => {
            console.error('Error stopping task:', error);
          });
    },
    statusFormatter(row) {
      switch (row.status) {
        case 0:
          return '待执行';
        case 1:
          return '执行中';
        case 2:
          return '已完成';
        case 3:
          return '失败';
        case 4:
          return '已停止';
        case 5:
          return '已暂停';
        default:
          return '未知状态';
      }
    }
  }
};
</script>

<style scoped>
.monitor {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
